package com.example.javaweb.web003.src;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

public class Upload extends HttpServlet {
    public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //上传文件
            SmartUpload su = new SmartUpload();
            //获得pageContext对象
            JspFactory factory = JspFactory.getDefaultFactory();
            PageContext pagecontext =
                    factory.getPageContext(this, request, response, null, false, 1024, true);
            su.initialize(pagecontext);
            su.setCharset("utf-8");
            //实现文件数据的上传
            su.upload();

            File file = su.getFiles().getFile(0);
            //得到文件的基本信息
            String filename = file.getFileName();
            String type = file.getContentType();
            System.out.println("type=" + type);
            String url = "uploadfile/" + filename;
            //将上传文件保存到指定目录
            file.saveAs(url, SmartUpload.SAVE_VIRTUAL);
            request.setAttribute("filename", filename);

            String uname = su.getRequest().getParameter("uname");
            System.out.println("uname=" + uname);
            request.getRequestDispatcher("success.jsp").forward(request,
                    response);

        } catch (SmartUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


}
